import { Injectable } from "@angular/core";
import { Observable, of, throwError } from "rxjs";
import {
  HttpClient,
  HttpHeaders,
  HttpErrorResponse
} from "@angular/common/http";
import { catchError, tap, map } from "rxjs/operators";

import { IOrderType } from "@/trade/store/models/trade";

export interface IStatusType {
  label: string;
  val: string;
  key: string;
}

const httpOptions = {
  headers: new HttpHeaders({ "Content-Type": "application/json" })
};
const apiUrl = "/config";

@Injectable({
  providedIn: "root"
})
export class ConfigService {
  public defQuerySymbol = {
    zi: "ETH",
    mu: "BTC"
  };

  public orderType: Array<IStatusType> = [
    {
      label: "buy",
      val: "1",
      key: "buy"
    },
    {
      label: "sell",
      val: "0",
      key: "sell"
    }
  ];

  public depositStatus: Array<IStatusType> = [
    {
      label: "deposit_status_add",
      val: "0",
      key: "add"
    },
    {
      label: "deposit_status_confirming",
      val: "1",
      key: "confirming"
    },
    {
      label: "deposit_status_waiting",
      val: "2",
      key: "waiting"
    },
    {
      label: "deposit_status_over",
      val: "3",
      key: "over"
    }
  ];

  public withdrawStatus: Array<IStatusType> = [
    {
      label: "withdraw_status_add",
      val: "0",
      key: "add"
    },
    {
      label: "withdraw_status_pass",
      val: "1",
      key: "pass"
    },
    {
      label: "withdraw_status_trading",
      val: "2",
      key: "trading"
    },
    {
      label: "withdraw_status_hash",
      val: "3",
      key: "hash"
    },
    {
      label: "withdraw_status_over",
      val: "4",
      key: "over"
    },
    {
      label: "withdraw_status_refused",
      val: "5",
      key: "refused"
    }
  ];

  public point = 8;

  constructor(private http: HttpClient) {}

  private handleError(error: HttpErrorResponse) {
    if (error.error instanceof ErrorEvent) {
      // A client-side or network error occurred. Handle it accordingly.
      console.error("An error occurred:", error.error.message);
    } else {
      // The backend returned an unsuccessful response code.
      // The response body may contain clues as to what went wrong,
      console.error(
        `Backend returned code ${error.status}, ` + `body was: ${error.error}`
      );
    }
    // return an observable with a user-facing error message
    return throwError("Something bad happened; please try again later.");
  }

  private extractData(res: Response) {
    const body = res;
    return body || {};
  }

  select(): Observable<any> {
    return this.http.get(apiUrl, httpOptions).pipe(
      map(this.extractData),
      catchError(this.handleError)
    );
  }
}
